<template>
  <!-- 采购变更 -->
  <div class="page-container">
    <ex_super_form ref="form" v-bind="option" v-loading="loading" class="common-form-row" label-position="right"
      label-width="140px">
    </ex_super_form>
    <el-form ref="elForm" :model="form" v-loading="loading" class="standard_form_gird standard_form_gird_right"
      label-position="right" label-width="140px">
      <ex_header_spiler :title="$t('label_base_info')"></ex_header_spiler>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_customer', '客户')" prop="customerName">
            {{ form.customerName }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_purchase_purchase_type', '采购类型')" prop="purchaseType">
            {{ $enumShow(form.purchaseType, 'PurchasePlatformTypeEnum') }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$t('label_supplier_good_name')" prop="supplierName">
            {{ form.supplierName }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$t('label_purchase_buyer')" prop="purchaser">
            {{ form.purchaser }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$t('label_purchase_apportioned_freight')" prop="apportionFreight">
            {{ $enumShow(form.apportionFreight, 'PurchaseApportionFreightEnum') }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$t('label_purchase_receiving_warehouse')" prop="warehouseName">
            {{ form.warehouseName }}
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$t('label_purchase_source')" prop="purchaseSource">
            {{ form.purchaseSource }}
          </el-form-item>
        </el-col>
        <el-col v-if="form.purchaseType==='GENERAL'">
          <el-form-item :label="$t('label_purchase_tracking_number')" prop="orderNo">
            {{ form.orderNo }}
          </el-form-item>
        </el-col>
        <el-col v-if="form.purchaseType==='ALIBABA'">
          <el-form-item :label="$t('label_platform_order_1688')" prop="platformOrderNo">
            {{ form.platformOrderNo }}
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <div class="mg_b3">
      <el-button @click="batchRemoval">
        {{ this.$tt('label_batch_remove') }}
      </el-button>
      <el-button @click="add">
        {{ this.$tt('label_supplier_add_goods') }}
      </el-button>
    </div>
    <ex_super_table ref="table" :model="buildTableModel" :data="rows" class="w_fill purchaseOrderCreationTable"
      @selection-change="e => selection = e">
      <template v-slot:purchaseQtyHeader="scope">
        <div class="flexBox">
          <div class="label_require_before">{{ $tt(scope.model.label) }}</div>
          (<div class="cubs" @click="purchaseQtyClick">{{ $tt('label_batch') }}</div>)
        </div>
      </template>
      <template v-slot:purchasePriceHeader="scope">
        <div class="flexBox">
          <div class="label_require_before">{{ $tt(scope.model.label) }}</div>
          (<div class="cubs" @click="purchasePriceClick">{{ $tt('label_batch') }}</div>)
        </div>
      </template>
    </ex_super_table>
    <div class="totalCard">
      <ex_super_form ref="totalForm" v-bind="totalOption" label-width="140px">
      </ex_super_form>
      <div class="statisticsCard">
        <div>
          <span>
            {{ $tt('label_article_category') }}：
          </span>
          <span>
            {{ rows.length }}
          </span>
        </div>
        <div>
          <span>
            {{ $tt('label_quantity_commodity') }}：
          </span>
          <span>
            {{ newSkuCount }}
          </span>
        </div>
        <div>
          <span>
            {{ $tt('label_purchase_total_purchase') }}：
          </span>
          <span>
            {{ newSkuTotalAmount }}
          </span>
        </div>
      </div>
    </div>
    <div class="mg_t2 footerSub">
      <div>
        <div>
          {{ $tt('label_transportation_expenses') }}{{ transportationExpenses }}
        </div>
        <div>
          {{ $tt('label_total_payable') }}{{ newTotalAmount }}
        </div>
      </div>
    </div>
    <div class="mg_t2">
      <el-button type="primary" @click="submitForm()">{{
      $tt("label_submit")
    }}</el-button>
      <el-button @click="return_page_back">{{ $tt("label_cancel") }}</el-button>
    </div>
    <add_supply_relationship_dialog ref="addSupplyRelationshipDialog" @selectData="selectData" :dialogData="dialogData"
      :selectData="true" :hasSelectList="rows" />
    <batch_dialog ref="batch_dialog" @submit="batchAmend" />

    <!-- 查看参考价 -->
    <history_purchase_order_dialog ref="historyPurchaseOrderDialog" :dialogData="dialogData" />
  </div>
</template>

<script>
import router_params from "@/mixin/router_params";
import add_supply_relationship_dialog from "@/page/oms/purchase/dialog/add_supply_relationship_dialog.vue"
import batch_dialog from "@/page/oms/purchase/dialog/batch_dialog.vue"
import history_purchase_order_dialog from "@/page/oms/purchase/dialog/history_purchase_order_dialog.vue"

export default {
  mixins: [router_params],
  components: {
    add_supply_relationship_dialog,
    batch_dialog,
    history_purchase_order_dialog,
  },
  props: {},
  data() {
    return {
      dialogData: {
        customerId: '', // 客户id
      },
      rows: [],
      selection: [],
      loading: false,
      form: {},
      option: {
        inputClass: "w_fill",
        model: [
          {
            grid: [
              [
                {
                  span: 2,
                  col: {
                    key: "changeReasons",
                    label: "label_reasons_change",
                    attrs: {
                      type: 'textarea',
                    },
                  },
                },
              ],
            ],
          },
        ],
        rules: {
          changeReasons: [
            {
              required: true,
              message: this.$tt("tip_can_no_empty"),
              trigger: "blur",
            },
          ],
        },
      },
      totalOption: {
        model: [
          {
            grid: [
              [
                {
                  col: {
                    label: 'label_purchase_freight',
                    key: 'newPurchaseFreight',
                    placeholder: 'label_optional',
                    on: {
                      input: (e) => {
                        const { newPurchaseFreight, newOtherCost } = this.$refs.totalForm.getFormData()
                        this.transportationExpenses = Number(newPurchaseFreight || 0) + Number(newOtherCost || 0)
                      }
                    },
                    attrs: {
                      type: 'number',
                    },
                  }
                },
                {
                  col: {
                    label: 'label_purchase_other_charges',
                    key: 'newOtherCost',
                    placeholder: 'label_optional',
                    on: {
                      input: (e) => {
                        const { newPurchaseFreight, newOtherCost } = this.$refs.totalForm.getFormData()
                        this.transportationExpenses = Number(newPurchaseFreight || 0) + Number(newOtherCost || 0)
                      }
                    },
                    attrs: {
                      type: 'number',
                    },
                  }
                },
                {
                  col: {
                    label: 'label_expected_arrival',
                    key: 'newPredictDay',
                    render: (h, { data, item }) => {
                      const items = [
                        { label: this.$t('label_day_within', ['1']), value: '1' },
                        { label: this.$t('label_day_within', ['3']), value: '3' },
                        { label: this.$t('label_day_within', ['5']), value: '5' },
                        { label: this.$t('label_day_within', ['7']), value: '7' },
                        { label: this.$t('label_day_within', ['9']), value: '9' },
                        { label: this.$t('label_day_within', ['15']), value: '15' },
                      ]
                      return h('ex_select_auto', {
                        props: {
                          value: data.newPredictDay,
                          items,
                        },
                        on: {
                          change: (e) => {
                            this.$set(data, item.key, e);
                          },
                        }
                      })
                    }
                  }
                },
              ]
            ]
          },
          {
            grid: [
              [
                {
                  // span: 1,
                  col: {
                    label: 'label_purchase_remark',
                    key: 'remark',
                    attrs:{
                      type: 'textarea',
                    }
                  }
                },
              ]
            ]
          },

        ]
      },
      transportationExpenses: 0,
      // 历史数据
      oldList: [],
      oldListIds:[],
      // 删除的数据
      delList: []
    };
  },
  watch: {},
  computed: {
    // 应付总额
    newTotalAmount() {
      let num = this.transportationExpenses + this.newSkuTotalAmount
      return num
    },
    // 商品数量
    newSkuCount() {
      let num = 0
      this.rows.forEach(item => {
        num += Number(item.newPurchaseQty || 0)
      })
      return num
    },
    // 采购总额
    newSkuTotalAmount() {
      let amount = 0
      this.rows.forEach(item => {
        amount += Number(item.newPurchaseTotalPrice || 0)
      })
      return amount

    },
    buildTableModel() {
      return [
        {
          type: 'selection',
        },
        {
          key: "skuName",
          label: "label_sku_info",
        },
        {
          key: "skuPrice",
          label: "label_reference_price",
        },
        {
          key: "newPurchaseQty",
          slot_header: "purchaseQtyHeader",
          label: "label_count",
          width: 160,
          render: (h, { row, column, index }) => {
            const onInput = (e) => {
              row[column.property] = e
              row['newPurchaseTotalPrice'] = Number(row.newPurchasePrice) * Number(row.newPurchaseQty)
              this.$set(this.rows, index, row)
            }
            return (<div class="flex-s">
              <div class="flex-t">
                <span class="label_before">{this.$tt('label_purchase_new')}:</span>
                <el-input type="number" value={row.newPurchaseQty} onInput={onInput} />
              </div>
              <div><span>{this.$tt('label_purchase_original')}:</span>{row.purchaseQty}</div>
            </div>)
          }
        },

        {
          key: "newPurchasePrice",
          label: "label_unit_price",
          slot_header: "purchasePriceHeader",
          width: 160,
          render: (h, { row, column, index }) => {
            const onInput = (e) => {
              row[column.property] = e
              row['newPurchaseTotalPrice'] = Number(row.newPurchasePrice) * Number(row.newPurchaseQty)
              this.$set(this.rows, index, row)
            }
            return (<div class="flex-s">
              <div class="flex-t">
                <span class="label_before">{this.$tt('label_purchase_new')}:</span>
                <el-input type="number" value={row.newPurchasePrice} onInput={onInput} />
              </div>
              <div><span>{this.$tt('label_purchase_original')}:</span>{row.purchasePrice}</div>
            </div>)
          }
        },
        {
          key: "historyPurchasePrice",
          label: "label_historical_purchase_price",
          formatter: (r, c, v, i) => (v ? v : "-"),
          render: (h, { row, column, index }) => {
            const showHistory = () => {
              this.$refs.historyPurchaseOrderDialog.show(row)
            }
            let divStr = ''
            if (row['historyPurchasePrice']) {
              divStr = <div onClick={showHistory} class="cubs">{row['historyPurchasePrice']}&nbsp;<i class="el-icon-s-data"></i></div>
            }
            return (
              divStr
            );
          }
        },
        {
          key: "newPurchaseTotalPrice",
          label: "label_purchase_subtotal",
          width: 150,
          render: (h, { row, column, index }) => {
            return (<div class="flex-s">
              <div class="flex-t">{this.$tt('label_purchase_new')}:&nbsp;&nbsp;{row.newPurchaseTotalPrice || '-'}</div>
              <div>{this.$tt('label_purchase_original')}:&nbsp;&nbsp;{row.purchaseTotalPrice || '-'}</div>
            </div>)
          }
        },
        {
          type: "operate",
          width: 150,
          operate: [
            {
              label: "label_delete",
              click: (row, i) => {
                this.deleteFn(this.rows, i)
              },
            },
          ],
        },
      ]
    },
  },
  created() { },
  mounted() { },
  methods: {
    batchAmend(data) {
      const { value, type } = data
      this.rows.forEach((item, index) => {
        item[type] = value
        item['newPurchaseTotalPrice'] = Number(item.newPurchasePrice) * Number(item.newPurchaseQty)
        this.$set(this.rows, index, item)
      })
    },
    purchasePriceClick() {
      if (this.rows.length) {
        this.$refs.batch_dialog.show({ title: this.$tt('label_revise_unit_price'), name: this.$tt('label_unit_price'), key: 'newPurchasePrice' })
      } else {
        this.$message.error(this.$tt('label_no_commodity_to_operate'))
      }
    },
    purchaseQtyClick() {
      if (this.rows.length) {
        this.$refs.batch_dialog.show({ title: this.$tt('label_revise_quantity'), name: this.$tt('label_count'), key: 'newPurchaseQty' })
      } else {
        this.$message.error(this.$tt('label_no_commodity_to_operate'))
      }
    },
    init_data_default(into_params) {
      if (into_params.id) {
        this.loading = true;
        this.$ajax({
          url: "/oms-api/purchase/OmsPurchaseOrderRpc/selectDetail.json",
          method: "post",
          data: { id: into_params.id },
          success: (res) => {
            if (!res.data)
              return this.$message.error(this.$tt("label_data_loss"));
            this.$nextTick(() => {
              if (res.data.purchaseFreight) this.transportationExpenses += Number(res.data.purchaseFreight)
              if (res.data.otherCost) this.transportationExpenses += Number(res.data.otherCost)
              this.$refs.totalForm.setData({
                newPurchaseFreight: res.data.purchaseFreight || '',
                newOtherCost: res.data.otherCost || '',
                newPredictDay: res.data.predictDay ? String(res.data.predictDay) : '',
                remark: res.data.remark || '',
              });
              this.dialogData.customerId = res.data.customerId
              this.dialogData.supplierName = res.data.supplierName
              this.dialogData.supplierId = res.data.supplierId
              this.form = res.data
              this.rows = res.data.omsPurchaseOrderDetailList.map(item => {
                this.oldListIds.push(item.skuId)
                item.newPurchaseQty = item.purchaseQty
                item.newPurchasePrice = item.purchasePrice
                item.newPurchaseTotalPrice = item.purchaseTotalPrice
                return item
              })
              this.oldList = JSON.parse(JSON.stringify(this.rows))
              this.$refs.form.clearValidate();
              this.$refs.totalForm.clearValidate();
            });
            this.fixTabLabel(res.data.code);
          },
          complete: () => {
            this.loading = false;
          },
        });
      }
    },
    fixTabLabel(code) {
      this.$emit("tagModifyLabel", {
        _key: "label_name_code",
        name: this.$t('label_purchase_change'),
        code: code || "",
      });
    },
    batchRemoval() {
      if (this.selection && this.selection.length) {
        const arr = []
        this.rows.forEach((item, i) => {
          if (this.selection.findIndex(op => op.id === item.id) !== -1) {
            arr.push(i)
          }
        })
        arr.reverse().forEach((op) => {
          this.deleteFn(this.rows, op)
        })
      } else {
        this.$message.error(this.$tt('tip_please_select_order'))
      }
    },
    deleteFn(target, index) {
      if(this.oldListIds.includes(target[index].skuId)){
        this.delList.push(target[index])
      }
      target.splice(index, 1);
    },
    // 添加
    add() {
      // this.$refs.form.$refs.form.validateField("customerId");
      if (this.dialogData.customerId) {
        this.$refs.addSupplyRelationshipDialog.show()
      }
    },
    selectData(data) {
      // 需要判断 如果列表里已有数据则不新增
      this.$refs.addSupplyRelationshipDialog.hide()
      let skuIds = []
      this.rows.forEach(item => {
        skuIds.push(item.skuId)
      })
      data.forEach(item => {
        if (!skuIds.includes(item.skuId)) {
          if (!item.purchasePrice) {
            item.newPurchasePrice = item.skuPrice
            item.purchasePrice = 0
            item.purchaseQty = 0
            item.purchaseTotalPrice = 0
          }
          // 如果删除列表里有数据 则使用删除的数据
          for (let index = 0; index < this.delList.length; index++) {
            const element = this.delList[index];
            if(element.skuId===item.skuId){
              item = element
              break
            }
          }

          this.rows.push(item)
        }
      })



      this.getHistoryPrice()
    },
    getHistoryPrice() {
      const skuIds = []
      this.rows.forEach(item => {
        skuIds.push(item.skuId)
      })
      this.$ajax({
        url: '/oms-api/purchase/OmsPurchaseOrderRpc/selectHistoryPrice.json',
        method: "post",
        type: "form",
        data: { skuIds },
        success: (res) => {
          if (res && res.data && res.data.rows.length > 0) {
            for (let index = 0; index < this.rows.length; index++) {
              const item = this.rows[index];
              for (let j = 0; j < res.data.rows.length; j++) {
                const item2 = res.data.rows[j];
                if (item.skuId === item2.skuId) {
                  this.$set(this.rows[index],'historyPurchasePrice',item2.skuPrice)
                  break
                }
              }
            }
          }

        },
      });
    },
    submitForm() {
      if (this.rows.length === 0) {
        return this.$message.error(this.$tt('tip_please_select_sku'))
      }
      if (this.rows.findIndex(item => !item.newPurchaseQty) !== -1) {
        return this.$message.error(this.$tt('label_quantity_goods_no_empty'))
      }
      if (this.rows.findIndex(item => !item.newPurchasePrice) !== -1) {
        return this.$message.error(this.$tt('label_unit_price_goods_no_empty'))
      }

      this.$refs["form"].validate((valid, obj) => {
        if (valid) {

          const form = JSON.parse(JSON.stringify(this.form))
          const purchaseOrderId = form.id
          const purchaseOrderCode = form.code
          delete form.omsPurchaseOrderDetailList
          delete form.id
          delete form.code
          const data = {
            ...form,
            purchaseOrderId,
            purchaseOrderCode,
            ...this.$refs.form.getFormData(),
            ...this.$refs.totalForm.getFormData(),
            omsPurchaseOrderDetailChangeList: this.dataHander(),//获取数据的 删除 修改 新增 无操作状态

            newSkuCategoryCount: this.rows.length,
            newSkuTotalAmount: this.newSkuTotalAmount,
            newSkuCount: this.newSkuCount,
            newTotalAmount: this.newTotalAmount,
          }
          this.$ajax({
            url: '/oms-api/purchase/OmsPurchaseChangeOrderRpc/change.json',
            method: "post",
            type: "json",
            loading: this.$tt("tip_submiting"),
            data,
            success: (res) => {
              this.$message.success(this.$tt("tip_submit_success"));
              this.return_emit(null, "reload");
              this.return_page_back();
            },
          });
        } else {
          this.$message.error(this.$tt("form_validate_error"));
          return false;
        }
      });
    },
    dataHander(){
      const genData = JSON.parse(JSON.stringify(this.rows))
      // 用来和删除列表比较 不包含的则表示删除,可能会有删除了又加进去
      const rowsSkuIds = []

      for (let index = 0; index < genData.length; index++) {
        const row = genData[index];
        rowsSkuIds.push(row.skuId)
        // 状态默认为新增，下面通过判断 改为无操作或修改
        genData[index].changeOperationType='ADD'
        for (let i = 0; i < this.oldList.length; i++) {
          const old = this.oldList[i];
          if(row.skuId===old.skuId){
            // 数量价格一致 则认为无操作
            if(row.newPurchasePrice==old.newPurchasePrice&&row.newPurchaseQty==old.newPurchaseQty){
              genData[index].changeOperationType='NO_OPERATION'
            }else{
              genData[index].changeOperationType='MODIFY'
            }
            break
          }
        }
      }


      this.delList.forEach(item=>{
        if(!rowsSkuIds.includes(item.skuId)){
          item.changeOperationType = 'DELETE'
          genData.push(item)
        }
      })

      return genData
    }
  },
  destroyed() { },
};
</script>

<style lang="less" scoped>
.purchaseOrderCreationTable {
  /deep/.ex_table_auto {
    margin-bottom: 0;
  }
}

.totalCard {
  width: 100%;
  box-sizing: border-box;
  min-height: 100px;
  padding: 18px 10px 0 10px;
  border: 1px solid #d9dfe7;
  border-top: none;
  display: flex;

  .el-form {
    flex: 1;
    flex-shrink: 0;
  }

  .statisticsCard {
    width: 300px;
    height: auto;
    color: #606266;

    >div {
      display: flex;
      margin-bottom: 5px;

      span {
        display: inline-block;
        width: 150px;

        &:first-child {
          text-align: right;
        }

        &:last-child {
          overflow-wrap: break-word;
        }
      }
    }
  }
}

.footerSub {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #606266;
  font-weight: 500;
  line-height: 25px;

  >div {
    display: flex;
    gap: 20px;
  }

}

.flexBox {
  display: flex;
  justify-content: center;
  align-items: center;
}

.cubs {
  color: #2ea7e0;
  cursor: pointer;
}

/deep/.flex-s {
  display: flex;
  flex-direction: column;
  text-align: left;

  >div {
    padding-left: 15px;

    >span {
      display: inline-block;
      padding-right: 8px;
      position: relative;
    }
  }

  .flex-t {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }

  .label_before::before {
    position: absolute;
    left: -8px;
    content: "*";
    color: red;
  }
}

/deep/.cubs {
  color: #2ea7e0;
  cursor: pointer;
}
</style>
